package Service;

import DAO.BookDAO;
import DATA.Book;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "addBook", value = "/addBook")
public class addBook extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bookName=request.getParameter("bookName");
        String bookType=request.getParameter("bookType");
        String author=request.getParameter("author");

        Book book=null;
        try {
            book= BookDAO.findByBookNameAndAuthor(bookName,author);
        } catch (SQLException e) {
            throw new RuntimeException("找唯一书失败");
        }
        if(book!=null){
            request.setAttribute("bookExists","书本已存在");
            request.getRequestDispatcher("insertBook.jsp").forward(request,response);
        }
        else{
            try {
                if(BookDAO.insertBook(bookName,bookType,author)){
                    //记得书本热度默认为0
                    //另外这里加了个触发器，new关键字表示新插入或更新的数据行的别名（也称为虚拟表）。
                    // 当触发器被触发时，MySQL会创建一个虚拟表，其中包含了待插入/更新的数据行。
                    //它表示第一个表中新插入数据行对应的id属性的值，这个值将用于更新第二个表中id属性相同的数据行所对应的某个属性的值。
                    //create TRIGGER books_after_insert AFTER INSERT on comments for each row
                    //BEGIN
                    //	UPDATE books SET recommend=recommend+1 WHERE books.id = new.bid;
                    //END;
                    //姜老师都没讲过啊，又是自己找方法的一天
                    request.getRequestDispatcher("BookList").forward(request,response);
                }
            } catch (SQLException e) {
                throw new RuntimeException("插入书本失败");
            }
        }
    }
}
